package com.xiaoze.sink;

import com.xiaoze.entity.SensorReading;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * SinkTestKafka
 *
 * @author Lin Zemin
 * @date 2021-12-28
 */
public class SinkTestKafka {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        String path = System.getProperty("user.dir") + "\\src\\main\\resources\\sensor.txt";
        DataStreamSource<String> inputStream = env.readTextFile(path);

        SingleOutputStreamOperator<String> dataStream = inputStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2])).toString();
        });

        KafkaSink<String> sink = KafkaSink.<String>builder()
                .setBootstrapServers("192.168.24.130:9092,192.168.24.130:9093,192.168.24.130:9094")
                .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                        .setTopic("topic3")
                        .setValueSerializationSchema(new SimpleStringSchema())
                        .build()
                )
                .build();

        dataStream.sinkTo(sink);
        env.execute();

    }

}
